package com.cs.peanut.base_app;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Created by zack on 2018/3/14.
 */

public class TCPUitls {

    public static int getIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifoInfo = wifiManager.getConnectionInfo();
        return wifoInfo.getIpAddress();
    }

    public static String int2Ip(int ip) {
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "."
                + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
    }

    public static int[] int2Ips(int ip) {
        return new int[]{(ip & 0xFF), +((ip >> 8) & 0xFF), ((ip >> 16) & 0xFF), (ip >> 24 & 0xFF)};
    }

    public static boolean canConnected(String ip, int port) {
        try {
            Socket socket = new Socket();//http://www.weixianmanbu.com/article/163.html
            SocketAddress socketAddress = new InetSocketAddress(ip, port);
            socket.connect(socketAddress, 1000);
            socket.close();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
        }
    }

}
